﻿angular.module('app')
    .controller('TopicCtrl', [
        "$scope", 'TopicSrv', '$timeout', '$q', 'WorkContextSrv', '$rootScope', '$document', function ($scope, topicSrv, $timeout, $q, workContextSrv, $rootScope, $document) {
            var currentUser = workContextSrv.getCurrentUser();
            var username = currentUser.userName;
            var defaultPageSize = 10;
            var defaultPageIndex = 0;
            var pageSize = defaultPageSize;
            var pageIndex = defaultPageIndex;
            var loadtm = null;

            $scope.topicList = {
                onLoading: false,
                stopLoading: false,
                noResult: false,
                results: [],
                firstLoad: true,
                onLoadingSingleTopic: false
            };

            $scope.topicSearch = {
                searchResult: [],
                showSearch: false,
                onSearching: false,
                query: '',
                status: '',
                showMessage: false
            };

            $scope.currentDate = [];
            $scope.showDate = function (date) {
                if ($scope.currentDate.indexOf(date) !== -1) {
                    return false;
                }

                $scope.currentDate.push(date);
                return true;
            }

            function searchTopic() {
                $scope.topicList.stopLoading = false;
                $scope.topicList.onLoading = false;

                $scope.topicSearch.onSearching = true;
                $scope.topicSearch.showSearch = true;
                $scope.topicSearch.searchResult = [];
                $scope.topicSearch.showMessage = false;
                topicSrv.searchTopics(username, $scope.topicSearch.query).success(function (data) {
                    $scope.topicSearch.searchResult = data;
                    $scope.topicSearch.showMessage = !data.length;
                    $scope.topicSearch.onSearching = false;
                    loadtm = null;
                }).error(function (dt) {
                    //if (typeof dt !== 'undefined' && dt != null) {
                    //    alert(dt.message);
                    //}
                    $scope.topicSearch.onSearching = false;
                });
            }

            //watch query change
            $scope.$watch('topicSearch.query', function () {
                //abort all previous request
                $rootScope.$broadcast("abortPendingRequest");

                pageSize = defaultPageSize;
                pageIndex = defaultPageIndex;
                if (!$scope.topicList.firstLoad) {
                    if ($scope.topicSearch.query === '') {
                        $scope.topicList.stopLoading = false;
                        $scope.topicList.noResult = false;
                        $scope.topicSearch.onSearching = false;
                        $scope.topicSearch.showSearch = false;
                        loadMoreTopics(true);
                    } else {
                        searchTopic();
                    }
                }
            });

            //on search result click
            $scope.chooseSearchItem = function (sitem, $event) {
                $scope.topicSearch.onSearching = true;
                $scope.topicList.results = [];
                if (!$scope.topicList.onLoadingSingleTopic) {
                    angular.element($event.target).addClass("selected");
                    $scope.topicList.onLoadingSingleTopic = true;
                    topicSrv.getTopicById(username, sitem.id).success(function (dt) {
                        if (dt.subjects.length) {
                            $scope.topicList.noResult = false;
                            $scope.topicList.results.push(dt.subjects[0]);
                        }
                        $scope.topicSearch.showSearch = false;
                        $scope.topicSearch.onSearching = false;
                        $scope.topicList.onLoadingSingleTopic = false;
                        $scope.topicList.stopLoading = true;
                    });
                }

            };

            //load topics function
            function loadMoreTopics(clear) {

                if (clear) {
                    $scope.topicList.results = [];
                    pageSize = defaultPageSize;
                    pageIndex = defaultPageIndex;
                    $scope.topicList.onLoading = false;
                    $scope.topicList.stopLoading = false;

                    $scope.currentDate = [];
                }

                if (!$scope.topicList.onLoading && !$scope.topicList.stopLoading) {
                    //abort all previous request
                    $rootScope.$broadcast("abortPendingRequest");

                    $scope.topicList.onLoading = true;
                    $scope.topicSearch.query = '';
                    topicSrv.getTopics(username, '', $scope.topicSearch.status, pageSize, pageIndex++, false)
                        .then(function () {
                            //if there is some to load more
                            if (!$scope.topicList.stopLoading) {

                                Array.prototype.push.apply($scope.topicList.results, topicSrv.topics.subjects);

                                if ($scope.topicList.results.length <= 0) {
                                    $scope.topicList.noResult = true;
                                }

                                //if the result lesser than pageSize then stop loading in future
                                if (topicSrv.topics.subjects.length < pageSize) {
                                    $scope.topicList.stopLoading = true;
                                }
                            }

                            if (pageIndex === 1) {
                                //clear topic counter when load topics
                                $rootScope.$broadcast("clearTopicCount");
                            }

                            $scope.topicList.firstLoad = false;
                            $scope.topicList.onLoading = false;
                            loadtm = null;
                        },
                        function (error) {
                            //if (typeof dt !== 'undefined' && dt != null) {
                            //    alert(dt.message);
                            //}
                            $scope.topicList.onLoading = true;
                        })
                        .then(function () {
                            $timeout(function () {
                                $rootScope.$broadcast('hidePreloading');
                            }, 500);
                        });
                }
            }

            //Infinity scroll
            $scope.loadMoreTopics = function () {
                $timeout(function () {
                    $scope.$apply(loadMoreTopics(false));
                }, 200);
            };

            //when topic added from create topic
            $scope.$on("globalTopicAdded", function (e, params) {
                var resp = params.data;
                if (resp.result) {
                    var newTopic = resp.message;
                    var replies = resp.replies;

                    var ix = $scope.currentDate.indexOf(resp.message.whenDay);
                    if (ix !== -1) {
                        if ($scope.topicList.results.length > 0) {
                            $scope.topicList.results[0].showDateDivider = false;
                            $scope.currentDate.splice(ix, 1);
                        }
                    }

                    $scope.topicList.results.unshift({ "status": "New", "title": null, "topicId": resp.topicId, "message": newTopic, "replies": replies });
                    //hide 'no topic' message when create new topic
                    $scope.topicList.noResult = false;
                } else {
                    //alert(resp.errorMessage);
                }
            });

            //handle reload topic event
            $scope.$on("reloadTopics", function () {
                $scope.topicList.stopLoading = false;
                $scope.topicList.noResult = false;
                loadMoreTopics(true);
            });

            //hide search result when click to outside
            $document.bind('click', function (e) {
                if (angular.element(e.target).parents(".topic-search").length === 0) {
                    $scope.$apply(function () {
                        $scope.topicSearch.onSearching = false;
                        $scope.topicSearch.showSearch = false;
                    });
                }
            });
        }
    ]);